package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.DeviceGroup;
import com.example.mapper.DeviceGroupMapper;
import com.example.service.DeviceGroupService;
import com.example.vo.DeviceGroupVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备分组业务逻辑层实现类
 *
 * @author system
 * @since 2024-01-01
 */
@Service
@Slf4j
public class DeviceGroupServiceImpl extends ServiceImpl<DeviceGroupMapper, DeviceGroup> implements DeviceGroupService {
    
    @Override
    public List<DeviceGroupVO> getAllGroupsWithImages() {
        try {
            // 获取所有分组，按排序和ID排序
            List<DeviceGroup> groups = this.list(
                new LambdaQueryWrapper<DeviceGroup>()
                    .orderByAsc(DeviceGroup::getSortOrder)
                    .orderByAsc(DeviceGroup::getId)
            );
            
            // 转换为VO（不填充设备图片，由Controller层处理）
            return groups.stream().map(group -> {
                DeviceGroupVO vo = new DeviceGroupVO();
                BeanUtils.copyProperties(group, vo);
                return vo;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取所有设备分组失败", e);
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveGroup(String groupName, String operator) {
        try {
            // 检查分组名称是否已存在
            long count = this.count(
                new LambdaQueryWrapper<DeviceGroup>()
                    .eq(DeviceGroup::getGroupName, groupName)
            );
            if (count > 0) {
                log.warn("分组名称已存在：{}", groupName);
                return false;
            }
            
            // 创建新分组
            DeviceGroup group = new DeviceGroup();
            group.setGroupName(groupName);
            group.setSortOrder(0); // 默认排序值
            group.setCreateTime(LocalDateTime.now());
            group.setCreateBy(operator);
            group.setUpdateTime(LocalDateTime.now());
            group.setUpdateBy(operator);
            
            boolean result = this.save(group);
            if (result) {
                log.info("设备分组创建成功，ID：{}，名称：{}", group.getId(), groupName);
            }
            return result;
        } catch (Exception e) {
            log.error("保存设备分组失败", e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateGroup(String id, String groupName, String operator) {
        try {
            // 检查分组是否存在
            DeviceGroup group = this.getById(id);
            if (group == null) {
                log.warn("设备分组不存在，ID：{}", id);
                return false;
            }
            
            // 检查分组名称是否重复（排除自己）
            long count = this.count(
                new LambdaQueryWrapper<DeviceGroup>()
                    .eq(DeviceGroup::getGroupName, groupName)
                    .ne(DeviceGroup::getId, id)
            );
            if (count > 0) {
                log.warn("分组名称已存在：{}", groupName);
                return false;
            }
            
            // 更新分组信息
            group.setGroupName(groupName);
            group.setUpdateTime(LocalDateTime.now());
            group.setUpdateBy(operator);
            
            boolean result = this.updateById(group);
            if (result) {
                log.info("设备分组更新成功，ID：{}，名称：{}", id, groupName);
            }
            return result;
        } catch (Exception e) {
            log.error("更新设备分组失败", e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteGroup(String id) {
        try {
            // 检查分组是否存在
            DeviceGroup group = this.getById(id);
            if (group == null) {
                log.warn("设备分组不存在，ID：{}", id);
                return false;
            }
            
            // 获取默认分组（ID为1的分组）
            DeviceGroup defaultGroup = this.getById(1L);
            if (defaultGroup == null) {
                log.error("默认分组不存在，无法删除分组：{}", id);
                return false;
            }
            
            // 将该分组下的设备图片移至默认分组（使用lambdaUpdate避免循环依赖）
            this.baseMapper.updateDeviceImageGroupId(id, String.valueOf(1L));
            
            // 删除分组
            boolean result = this.removeById(id);
            if (result) {
                log.info("设备分组删除成功，ID：{}，名称：{}", id, group.getGroupName());
            }
            return result;
        } catch (Exception e) {
            log.error("删除设备分组失败", e);
            return false;
        }
    }
} 